<template>
  <BaseForm v-model="formDataModel" @close="$emit('callBack')" />

</template>

<script lang="tsx" setup>
import type { FormInstance } from 'element-plus'
import InspectInfoApi from '/@/api/webPath/InspectInfoApi.ts';
import { translate } from "/@/i18n";
import FORM_FIELD_TYPE from "/@/constants/FormFieldType.ts";
import InspectInfoBaseApi from '~/src/api/webPath/InspectInfoBaseApi';
import InspectInfoDetailApi from '~/src/api/webPath/InspectInfoDetailApi';
import SysAreaApi from '~/src/api/common/SysAreaApi';
import { ref } from 'vue'

defineOptions({
  name: 'InspectInfoEdit',
})

const props = defineProps({
  modelValue: {
    type: Object, // 明确指定类型
    default: () => ({}) // 提供默认值
  }
})

const emit = defineEmits(['fetch-data', 'callBack'])

const formRef = ref<FormInstance>();
const title = ref<string>('');
const dialogFormVisible = ref<boolean>(false);
const fixedItems = ref<Record<any, any>[]>([])
const townList = ref([])

const date = new Date()
const currentDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`

// onMounted(() => {
//   getList()
// })
// const data = { checkType: 1 }
// function getList() {
//   InspectInfoApi.templateList(data).then((res) => {
//     console.log(1234567890, res);

//   })
// }

// 动态生成自查填写项目
async function generateFormItems(obj: any) {
  const { data: { data } } = await InspectInfoBaseApi.inspectInfoList(obj)
  console.log("template list", data)
  const checkFieldItems: any[] = []

  // 创建一个 Date 对象，表示当前时间
  const now = new Date();

  // 获取年份
  const year = now.getFullYear(); // 获取完整的年份（例如：2023）
  // 获取月份
  const month = now.getMonth() + 1; // 获取月份（0-11，0 表示 1 月，所以需要 + 1）
  // 获取日期
  const day = now.getDate(); // 获取日期（1-31）
  // 获取小时
  const hours = now.getHours(); // 获取小时（0-23）
  // 获取分钟
  const minutes = now.getMinutes(); // 获取分钟（0-59）
  // 获取秒数
  const seconds = now.getSeconds(); // 获取秒数（0-59）
  // 格式化年月日
  const yearMonthDay = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
  // 格式化时分秒
  const hoursMinutesSeconds = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  // 创建一个 ref 来存储日期范围的默认值
  const defaultDateRange = ref<string[]>([]); // 修改：使用 ref 来存储日期范围

  const sortedData = data.sort((a, b) => +a.num - +b.num)
  console.log("sorted data", sortedData)
  const description = [
    {
      divider: "打分说明"
    },
    {
      clearable: true,
      type: FORM_FIELD_TYPE.TITLE,
      height: "200px",
      expandColumn: true,
      props: {
        rows: 5
      },
      title: sortedData[0].des,
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
    },
    {
      field: "explainText",
      value: sortedData[0].des,
      isShow: () => false,
      type: FORM_FIELD_TYPE.READONLY,
    },
    {
      divider: "检查详情"
    },
    // {
    //   label: "问题图片",
    //   field: "fileList",

    //   type: FORM_FIELD_TYPE.UPLOAD,
    //   config: {
    //     includeName: true,
    //     limit: 10,
    //     disabled: true,
    //   }
    // }
  ]
  sortedData.forEach((x: any, index: number) => {

    // 编辑数据的情况
    if (props.modelValue.query.inspectInfoId) {
      checkFieldItems.splice(0, 0,
        {
          field: `id-${index}`,
          isShow: () => false,
          type: FORM_FIELD_TYPE.READONLY,
        },
      )
    }

    checkFieldItems.push(...[
      {
        // title: `${x.checkSerial}.${x.checkItem}-${x.checkKey}`,
        title: `${index + 1}. ${x.checkItem}-${x.checkMatterNum}-${x.checkMatterDescribe} -对应条款：${x.term} ---分值：${x.deductPoints}分`,
        field: `desc-${index}`,
        value: `${x.checkItem}-${x.checkMatterNum}-${x.checkMatterDescribe} -对应条款：${x.term} ---分值：${x.deductPoints}分`,
        expandColumn: true,
        type: FORM_FIELD_TYPE.TITLE,
        labelField: true
      },
      {
        field: `num-${index}`,
        value: x.num,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
        config: {
          disabled: true,
        },
      },
      {
        field: `checkItem-${index}`,
        value: x.checkItem,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      {
        field: `checkMatterDescribe-${index}`,
        value: x.checkMatterDescribe,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      {
        field: `term-${index}`,
        value: x.term,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      {
        field: `checkMatterNum-${index}`,
        value: x.checkMatterNum,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      {
        field: `deductPoints-${index}`,
        value: x.deductPoints,
        isShow: () => false,
        type: FORM_FIELD_TYPE.READONLY,
      },
      // {
      //   field: `checkKey-${index}`,
      //   value: x.checkKey,
      //   isShow: () => false,
      //   type: FORM_FIELD_TYPE.READONLY,
      // },
      {
        label: "是否符合",
        field: `isStandard-${index}`,
        type: FORM_FIELD_TYPE.SINGLE_LAYER_SELECT,
        disabled: true,
        defaultValue: "是",
        options: x.isStandardList.map(x => ({ label: x, value: x })),
        callback: (handlers: any, v: any) => {
          if (["是", "不适用"].includes(v)) {
            handlers.updateParam(`problem-${index}`, "/")
            handlers.updateParam(`correction-${index}`, "/")
          } else {
            handlers.updateParam(`problem-${index}`, x.problemList[0])
            handlers.updateParam(`correction-${index}`, x.correctionList[0])
          }
        }
      },
      {
        label: "发现问题",
        field: `problem-${index}`,
        defaultValue: "/",
        options: x.problemList.map(x => ({ label: x, value: x })),
        inputType: "textarea",
        inputProps: {
          rows: 5
        },
        type: FORM_FIELD_TYPE.TEXTAREA,
        config: {
          disabled: true,
        },
      },
      {
        label: "整改措施",
        field: `correction-${index}`,
        defaultValue: "/",
        inputType: "textarea",
        inputProps: {
          rows: 5
        },
        disabled: true,
        options: x.correctionList.map(x => ({ label: x, value: x })),
        type: FORM_FIELD_TYPE.TEXTAREA,
        config: {
          disabled: true,
        },
      },
    ])
    if (props.modelValue.query.inspectInfoId) {
      checkFieldItems.push({
        label: "问题图片",
        disabled: true,
        field: `imgUrl-${index}`,
        type: FORM_FIELD_TYPE.IMG,
      })
    }
  })
  fixedItems.value.splice(0, fixedItems.value.length, ...formDataModel.value.items.filter(x => x.fixed))
  console.log("checkFieldItems", checkFieldItems)
  formDataModel.value.items = [...fixedItems.value, ...description, ...checkFieldItems]
  console.log("formDatamodel items ")
}

const formDataModel = ref({
  columnCount: 1,
  expandLimit: 6,
  autoFit: false,
  save: false,
  columnWidth: '300px',
  labelPosition: 'right',
  labelWidth: '120px',
  modelData: {},  //表单参数值 初始化
  callback: async (any: object) => {  //表单执行成功后回调
    console.log("callback any", any)
    //完成数据提交
    const inspectInfo = {
      id: any.id,
      serialNum: any.serialNum,
      serialName: any.serialName,
      serialType: any.serialType,
      provinceId: any.provinceId,
      provinceName: any.provinceName,
      cityId: any.cityId,
      cityName: any.cityName,
      areaId: any.areaId,
      areaName: any.areaName,
      townId: any.townId,
      name: any.name,
      address: any.address,
      examinerOne: any.examinerOne,
      examinerTwo: any.examinerTwo,
      inspectTime: any.inspectTime,
      dataSource: +any.dataSource,
      reviser: any.reviser,
      businessLicenseUrl: any.businessLicenseUrl,
      certificateUrl: any.certificateUrl,
      explainText: any.explainText,
    };

    const inspectInfoDetalList: any[] = [];
    for (const key of Object.keys(any)) {
      const keyList = ["num", "isStandard", "problem", "director", "correction", "desc", "checkItem", "checkMatterDescribe", "term", "checkMatterNum", "deductPoints", "imgUrl",]
      if (props.modelValue.query.inspectInfoId) {
        keyList.splice(0, 0, "id")
      }
      if (keyList.includes(key.split("-")[0]) && key.split("-").length > 1) {
        const [fieldName, index] = key.split("-")
        const indexNum = +index;
        if (!inspectInfoDetalList[indexNum]) {
          inspectInfoDetalList[indexNum] = {};
        }
        inspectInfoDetalList[indexNum][fieldName] = any[key];
      }
    }

    // 在这里添加 inspectBaseId
    // const { data: templateData } = await InspectInfoApi.templateList({ checkType: 1 });
    const { data: { data: templateData } } = await InspectInfoBaseApi.inspectInfoList({
      serialNum: any.serialNum,
      serialName: any.serialName,
      serialType: any.serialType,
    })
    console.log("templateData", templateData)
    templateData.forEach((item: any, index: number) => {
      if (inspectInfoDetalList[index]) {
        inspectInfoDetalList[index].inspectBaseId = item.id;
      } else {
        inspectInfoDetalList[index] = { inspectBaseId: item.id, };
      }
    });


    const obj = {
      fileList: any.fileList,
      inspectInfo: inspectInfo, // 将 inspectInfo 放入数组中
      inspectInfoDetailList: inspectInfoDetalList,
    };

    const { message } = await InspectInfoApi.batchSaves(obj)
    $baseMessage(message, 'success', 'vab-hey-message-success');

    emit('callBack', any); //把表单数据推送到上一层
  },
  items: [
    {
      label: "打分表类型",
      field: "serialType",
      clearable: true,
      fixed: true,
      serialNumField: "serialNum",
      serialTypeField: "serialType",
      serialNameField: "serialName",
      type: FORM_FIELD_TYPE.DYNAMIC_CASCADER_SELECT,
      disabled: true,
      onChange(params: any) {
        console.log("onchange ", params)
        generateFormItems(params)
      },
      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },

    },
    {
      label: "所属区域",
      field: "areaId",
      clearable: true,
      fixed: true,
      type: FORM_FIELD_TYPE.CITY_SELECT,
      provinceIdField: "provinceId",
      provinceNameField: "provinceName",
      cityIdField: "cityId",
      cityNameField: "cityName",
      areaIdField: "areaId",
      areaNameField: "areaName",
      onChange: async (v: any) => {
        console.log("selected change", v)
        const data = await SysAreaApi.getSysTownList({ areaId: v })
        if (data) {
          const { data: townDataList } = data
          townList.value = townDataList.map(x => ({ label: x.town, value: x.areaId }))
        }
        console.log("current town data", data)
      },
      // render(){
      //   return <CitySelect />
      // },
      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    },
    {
      label: "所属乡镇/街道",
      field: "townName",
      clearable: true,
      fixed: true,
      type: FORM_FIELD_TYPE.INPUT,
      options: townList,
      disabled: true,
      // render(){
      //   return <CitySelect />
      // },
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    },

    {
      label: "供应商名称",
      field: "name",
      clearable: true,
      fixed: true,
      type: FORM_FIELD_TYPE.INPUT,
      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    },
    {
      label: "供应商地址",
      field: "address",
      clearable: true,
      fixed: true,
      type: FORM_FIELD_TYPE.INPUT,
      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    },
    {
      label: "检查人1",
      field: "examinerOne",
      clearable: true,
      fixed: true,
      type: FORM_FIELD_TYPE.INPUT,
      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    },
    {
      label: "检查人2",
      field: "examinerTwo",
      clearable: true,
      fixed: true,
      type: FORM_FIELD_TYPE.INPUT,
      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    },
    {
      label: "检查时间",
      field: "inspectTime",
      fixed: true,
      clearable: true,
      type: FORM_FIELD_TYPE.INPUT,
      defaultValue: currentDate,

      placeholder: "请输入",
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    },
    {
      label: "营业证",
      field: "businessLicenseUrl",
      // fieldFormat: "img"
      fixed: true,
      type: FORM_FIELD_TYPE.UPLOAD,
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    },
    {
      label: "许可证",
      field: "certificateUrl",
      // fieldFormat: "img"
      disabled: true,
      fixed: true,
      type: FORM_FIELD_TYPE.UPLOAD,
      rule: {
        trigger: 'blur',
        validator: (rule: any, value: any, callback: any) => {  //绑定验证
          callback();
        },
      },
      config: {
        disabled: true,
      },
    }
  ],
})


onMounted(async () => {

  //初始化数据model
  if (props.modelValue.query) { //跳转过来时候有参数
    if (props.modelValue.query.inspectInfoId) {  //id存在则为编辑或复制，加载网络数据，如上级页面带参数手动覆盖
      const isCopy = props.modelValue.query.isCopy === true; // 检查是否为复制操作
      const { data: { dataSource, ...data } } = await InspectInfoApi.getDetail({
        inspectInfoId: props.modelValue.query.inspectInfoId   //从路由中获取参数
      })
      const { data: { records: detailData } } = await InspectInfoDetailApi.getPageData({
        inspectInfoId: props.modelValue.query.inspectInfoId,   //从路由中获取参数
        _size: 999,
        _current: 1
      })

      // 初始化乡镇下拉列表
      const townData = await SysAreaApi.getSysTownList({ areaId: data.areaId })
      if (townData) {
        const { data: townDataList } = townData
        townList.value = townDataList.map(x => ({ label: x.town, value: x.areaId }))
      }

      console.log("detail Data", detailData)
      const detailObj = {}
      const sortedDetailData = detailData.sort((a, b) => +a.num - +b.num)
      console.log("sortedDetailData", sortedDetailData)
      sortedDetailData.forEach((item, index) => {
        console.log("item", item)
        for (const key of Object.keys(item).filter(x => ["id", "isStandard", "problem", "director", "correction", "desc", "checkItem", "checkMatterDescribe", "term", "checkMatterNum", "deductPoints", "imgUrl"].includes(x))) {
          console.log("key", key)
          detailObj[`${key}-${index}`] = item[key]
        }
      })
      console.log("detailObj", detailObj)
      console.log("formDataModel.value.modelData", formDataModel.value.modelData)
      console.log("query 111 data", data)
      const { inspectTime, ...rest } = data

      // 如果是复制操作，则清空 id 相关字段
      if (isCopy) {
        formDataModel.value.modelData = { dataSource: +dataSource, ...rest, inspectTime: inspectTime.split(" ")[0], ...detailObj };
        delete formDataModel.value.modelData.id; // 删除主表id
        for (let i = 0; i < sortedDetailData.length; i++) {
          delete detailObj[`id-${i}`]; // 删除明细表id
        }
      } else {
        formDataModel.value.modelData = { dataSource: +dataSource, ...rest, inspectTime: inspectTime.split(" ")[0], ...detailObj };
      }
      console.log("formdata modelData", formDataModel.value.modelData)
    } else {
      //新增时候则用父类页面传参默认填充可根据业务修改
      for (const key in props.modelValue.query) {
        formDataModel.value.modelData[key] = props.modelValue.query[key]
      }
    }
  }
})


//方法暴露区域  todo
defineExpose({

})
</script>
